package com.mall.service.impl;

import com.mall.common.model.GlobalResponse;
import com.mall.dao.CategoryMapper;
import com.mall.pojo.Category;
import com.mall.service.ICategoryService;
import com.mall.vo.CategoryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public GlobalResponse<List<CategoryVO>> selectAll() {
        List<Category> categories = categoryMapper.selectAll();
        /*顶级目录*/
        List<CategoryVO> primaryCategoryVOList = categories.stream()
                .filter(category -> category.getParentId() == 0)
                .map(this::category2CategoryVO)
                .collect(Collectors.toList());
        primaryCategoryVOList.sort(Comparator.comparing(CategoryVO::getSortOrder).reversed());
        /*总目录*/
        List<CategoryVO> allCategoryVOList = categories.stream()
                .map(this::category2CategoryVO)
                .collect(Collectors.toList());

        /*递归注入多级目录*/
        recursion(primaryCategoryVOList, allCategoryVOList);
        return GlobalResponse.successByData(primaryCategoryVOList);
    }

    @Override
    public void findSubCategoryId(Integer id, Set<Integer> resultSet) {
        List<Category> categories = categoryMapper.selectAll();
        findSubCategoryId(id,resultSet,categories);
    }

    private void findSubCategoryId(Integer id, Set<Integer> resultSet,List<Category> categories){
        for (Category category : categories) {
            if (category.getParentId().equals(id)){
                resultSet.add(category.getId());
                findSubCategoryId(category.getId(),resultSet,categories);
            }
        }
    }

    private void recursion(List<CategoryVO> primaryCategoryVOList, List<CategoryVO> allCategoryVOList) {
        if (primaryCategoryVOList.isEmpty()) return;
        for (CategoryVO primaryCategoryVO : primaryCategoryVOList) {
            List<CategoryVO> subCategoryVOList = new ArrayList<>();
            for (CategoryVO subCategoryVO : allCategoryVOList) {
                if (Objects.equals(subCategoryVO.getParentId(), primaryCategoryVO.getId())) {
                    subCategoryVOList.add(subCategoryVO);
                }
            }
            /*排序*/
            subCategoryVOList.sort(Comparator.comparing(CategoryVO::getSortOrder).reversed());
            primaryCategoryVO.setSubCategories(subCategoryVOList);
            /*递归找到多级目录*/
            recursion(subCategoryVOList, allCategoryVOList);
        }
    }

    private CategoryVO category2CategoryVO(Category category) {
        CategoryVO categoryVO = new CategoryVO();
        BeanUtils.copyProperties(category, categoryVO);
        return categoryVO;
    }
}
